#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <pthread.h>
#define MASTER_PORT     8888
#define SLAVER_PORT     8889
#define BACKLOG 2

void *master_server(void *arg)
{
    int ss, sc; // ss 服务器socket描述符 sc 客户端socket描述符
    struct sockaddr_in server_addr; // 服务器地址结构
    struct sockaddr_in client_addr; // 客户端地址结构
    int err;    // 返回值
    printf("master server thread start up.\n");
    ss = socket(AF_INET, SOCK_STREAM, 0);
    if(ss < 0)
    {
        printf("socket errof\n");
        goto __exit;
    }

__exit:
    pthread_cancel(*(pthread_t *)arg);
}

void *slaver_server(void *arg)
{
    printf("slaver server thread start up.\n");

}

int main(int argc, char **argv)
{
    pthread_t tid_server, tid_slaver;

    if(pthread_create(&tid_server, NULL, master_server, &tid_slaver))
    {
        perror("Fail to create master server thread.\n");
        return -1;
    }

    if(pthread_create(&tid_slaver, NULL, slaver_server, NULL))
    {
        perror("Fail to create slaver server thread.\n");
        return -1;
    }

    pthread_join(tid_server, NULL);
    pthread_join(tid_slaver, NULL);
    printf("end.\n");
    return 0;
}

int main(int argc, char **argv)
{
    int ss, sc; // ss 服务器socket描述符 sc 客户端socket描述符
    struct sockaddr_in server_addr; // 服务器地址结构
    struct sockaddr_in client_addr; // 客户端地址结构
    int err;    // 返回值
    pid_t pid;  // 分叉得进行ID

    ss = socket(AF_INET, SOCK_STREAM, 0);
    if(ss < 0)
    {
        printf("socket errof\n");
        return -1;
    }

    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(PORT);

    err = bind(ss, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if(err < 0)
    {
        printf("bind error\n");
        return -1;
    }

    err = listen(ss, BACKLOG);
    if(err < 0)
    {
        printf("listen error\n");
        return -1;
    }

    while(1)
    {
        int addrlen = sizeof(struct sockaddr);

        sc = accept(ss, (struct sockaddr *)&client_addr, &addrlen);
        
        if(sc < 0) continue;

        pid = fork();
        if(pid == 0)
        {
            close(ss);  // 在子进程中关闭服务器的侦听
            process_conn_server(sc);
        }
        else 
        {
            close(sc);  // 在父进程中关闭客户端的连接
        }
    }
    return 0;
}

// void process_conn_server(int s)
// {
//     ssize_t size = 0;
//     char buffer[1024];
    
//     while(1)
//     {
//         size = read(s, buffer, 1024);

//         if(size == 0) return ;

//         sprintf(buffer, "%d bytes altogether\n", size);
//         write(s, buffer, strlen(buffer)+1);
//     }
// }
